import Base from "./Base"
import turf from "turf"
import mapboxgl from "mapbox-gl";



export default class MeasureArea extends Base{

  constructor(map,{callBack:callBack=null,errorCallBack:errorCallBack=null}={}) {
    super(map,'MeasureArea',{callBack:callBack,errorCallBack:errorCallBack});
  }


  start() {
    super.start();
    this.draw = new MapboxDraw({
      displayControlsDefault: false,
      controls: {}}
    );
    this.map.addControl(this.draw);
    this.draw.changeMode(this.draw.modes.DRAW_POLYGON);
    this.event=(e)=>{
      console.log(e);
      this.update(e)
    };
    this.eventFinish=(e)=>{
      if(e.features&&e.features.length>0){
        e.feature=e.features[0];
        this.update(e)
      }
    };
    this.map.on('draw.update_polygon',this.event);
    this.map.on('draw.create', this.eventFinish);
  }

  update(e){
    this.clearPopup();
    let area=turf.area(e.feature);
    let center=turf.center(e.feature);

    this.popup = new mapboxgl.Popup({
      closeButton: false,
      closeOnClick:false,
      className:this.popupClassName
    });
    this.popup.setLngLat(center.geometry.coordinates)
      .setText((area*0.0015).toFixed(2)+"亩")
      .addTo(this.map);
  }

  /**
   * 移除长度文字
   */
  clearPopup(){
    if(this.popup){
      this.popup.remove();
      this.popup=null;
     super.clearPopup();
    }
  }
  close() {
    this.clear();
    this.clearEvent();
  }

  clear() {
    this.clearPopup();
    this.clearMap();
  }

  clearMap() {
    if(this.draw){
      this.draw.deleteAll();
    }
  }

  clearEvent() {
    super.clearEvent();
    this.map.off('draw.update_polygon',this.event);
    this.map.off('draw.create',this.eventFinish);
    if(this.draw){
      this.map.removeControl(this.draw);
      this.draw=null;
    }
  }
}
